package com.heima.socket.udp.multicast;

import java.io.IOException;
import java.net.*;

public class ReveiveDemo1 {
    public static void main(String[] args) throws IOException {

        MulticastSocket ms = new MulticastSocket(10000);

        // 将当前本机添加到 224.0.0.1
        InetAddress address = InetAddress.getByName("224.0.0.1");
        ms.joinGroup(address);

        // 2. 接收数据
        byte[] bytes = new byte[1024];
        DatagramPacket dp = new DatagramPacket(bytes, bytes.length);

        ms.receive(dp);

        // 3. 解析数据
        byte[] data = dp.getData();
        int len = dp.getLength();
        String ip = dp.getAddress().getHostAddress();
        String name = dp.getAddress().getHostName();

        System.out.println("接收到数据: " + new String(data, 0, len));
        System.out.println("该数据是从" + name + "/" + ip + "发出的");

        // 4. 释放资源
        ms.close();
    }
}
